$(document).ready(function () {
    $.fn.zTree.init($("#treeDemo"), setting);
})
var setting = {
    view: {
        dblClickExpand: false,
        selectedMulti: false,           // 禁止多点同时选中的功能
        addHoverDom: addHoverDom,       //当鼠标移动到节点上时，显示用户自定义控件
        removeHoverDom: removeHoverDom, //离开节点时的操作
    },
    edit:{
        enable: true,                   //单独设置为true时，可加载修改、删除图标
        editNameSelectAll: true,
        removeTitle:"删除",       // 删除按钮的 Title 辅助信息
        renameTitle:"修改"       // 编辑名称按钮的 Title 辅助信息。
    },
    check: {
        enable: false
    },
    data: {
        key: {
            checked: "checked",
            children: "children",
            name: "orgName",
            title: "",
            url: ""
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: ""
        }
    },
    async: {
        enable: true,
        url: "../organ/query",
        dataFilter: filter
    },
    callback: {
        /*onRename: onRename,  */        //修改事件
        beforeRename : beforeRename,  //修改前的回调函数
        beforeRemove:beforeRemove,     //删除前的回调函数
        onRemove:onRemove,
        onAsyncSuccess:openzTree
    }
};

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i = 0, l = childNodes.length; i < l; i++) {
        childNodes[i].orgName = childNodes[i].orgName.replace(/\.n/g, '.');
    }
    return childNodes;
}

//树结构加载成功后展开根节点
function openzTree(event,treeId,treeNode,msg){
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    var node = zTree.getNodeByParam("id", 1);
    zTree.selectNode(node);
    zTree.expandNode(node, true, false, false);
}

//当鼠标移动到节点上时，显示用户自定义控件
function addHoverDom(treeId, treeNode) {
    treeNodes = treeNode;
    var sObj = $("#" + treeNode.tId + "_span"); //获取节点信息
    if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;

    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增' onfocus='this.blur();'></span>"; //定义添加按钮
    sObj.after(addStr); //加载添加按钮
    var btn = $("#addBtn_"+treeNode.tId);
    //绑定添加事件，并定义添加操作
    if (btn) btn.bind("click", function(){
        $("#addOrginDialog").modal("show");
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        var data = getFilePath(treeNode);
        $("#wholeName").val(data);
        var nodeLength = data.split("-");
        $("#orgLevel").val(nodeLength.length + 1);
        $("#parentId").val(treeNode.id);
    })
}

/*新增按钮点击提交事件*/
function submitaddOrgin(){
    var formData = $("#addOrginForm").serialize();
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    var orgName = $("#orgName").val();
    $.ajax({
        url: "../organ/insert",
        data: formData,
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.code == 1) {
                var newID = data.id; //获取新添加的节点Id
                zTree.addNodes(treeNodes, {id:newID, parentId:treeNodes.id, orgName:orgName}); //页面上添加节点
                var node = zTree.getNodeByParam("id", newID, null); //根据新的id找到新添加的节点
                zTree.selectNode(node); //让新添加的节点处于选中状态
                layer.msg(data.mess, {icon: 1});
                $("#addOrginDialog").modal("hide");
                $("#orgName").val("");
            } else if (data.code == 0) {
                layer.msg(data.mess, {icon: 2});
            }
        }
    })
}
//removeHoverDom执行销毁功能，消除由addHoverDom带给我们的操作
function removeHoverDom(treeId, treeNode) {
    $("#addBtn_"+treeNode.tId).unbind().remove();
};

/*function onRename(e, treeId, treeNode, isCancel) {
    if(treeNode.id=="1"){
        layer.msg("根节点不可改");
        return false;
    }
}*/
/********************新增结束**********************/
function beforeRename(treeId, treeNode, newName, isCancel){
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    if(newName==""){                  // 新名称为空的情况
        layer.msg("名称不能为空！");
        return false;
    } else if(newName!=treeNode.orgName){     // 如果新名称与就名称一致，什么也不做
       /* var zTree = $.fn.zTree.getZTreeObj("treeDemo");*/
        var data = getFilePath(treeNode);
        var newDate = data.split("-");
        var newList = "";
        if (newDate.length > 1) {
            var list = newDate.slice(0, -1);
            for (var i = 0; i < list.length; i++) {
                newList += list[i] + "-";
            }
        } else {
            newList = newDate[0];
        }
        var wholeName = newList;
        var nodeLength = data.split("-");
        var orgLevel = nodeLength.length + 1;
        var parentId = treeNode.parentId;
        var id = treeNode.id;
        $.ajax({
            url:"../organ/update",     //更改请求
            data : {id:id,orgName:newName,parentId:parentId,wholeName:wholeName,orgLevel:orgLevel},
            cache : false,
            dataType : 'JSON',
            type:'post',
            success: function(data){
                if (data.code == 1) {
                    layer.msg(data.mess, {icon: 1});
                }else{      //修改失败，即同一父类型下不能名称相同（我自己加的限制条件，你可以根据需要修改）
                    var node = treeNode.getParentNode();
                    zTree.reAsyncChildNodes(node, "refresh");  //回到旧名称
                }
            }
        });
    }
}
/*****************修改结束*********************/
function onRemove(treeId, treeNode){
    layer.confirm('确定要删除所选数据？', {icon: 3, title: '提示'}, function () {
           $.ajax({
               url: "../organ/delete",
               data: {"id": treeNode.id},
               type: "post",
               dataType: "json",
               success: function (data) {
                   if (data.code == 1) {
                       layer.msg(data.mess, {icon: 1});
                   } else if (data.code == 0) {
                       layer.msg(data.mess, {icon: 2});
                       return false;
                   }
               }
           })
       })
}
function beforeRemove (treeId, treeNode){//删除节点之前
    var flag=false;//此处必须定义一个变量，不然还没确定就把节点从树上删除
    if(treeNode.id=="1"){
        layer.msg("根节点不可删除");
        return false;
    }
    layer.confirm("确认删除当前节点吗？", {
        btn: ['确定','取消']
    }, function(){
        $.ajax({
            url: "../organ/delete",
            data: {"id": treeNode.id},
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.code == 1) {
                    flag=true;
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    var nodes = zTree.getSelectedNodes();
                    zTree.removeNode(treeNode);
                    layer.msg(data.mess, {icon: 1});
                } else {
                    layer.msg(data.mess, {icon: 2});
                }
            }
        })
    }   , function(index){
        layer.close(index);
        flag=false;
    })
    return flag;
}
/*获取所有父节点名称*/
function getFilePath(treeObj) {
    if (treeObj == null) return "";
    var filename = treeObj.orgName;
    var pNode = treeObj.getParentNode();
    if (pNode != null) {
        filename = getFilePath(pNode) + "-" + filename;
    }
    return filename;
}